package models.tasks

import java.sql.Timestamp

import javax.inject.Inject
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import scala.concurrent.ExecutionContext

class JobsRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext)
  extends HasDatabaseConfigProvider[JdbcProfile] {

  import profile.api._

  private class JobsTable(tag: Tag) extends Table[JobInfo](tag, "TASKS_JOBS") {
    def id = column[String]("id".toUpperCase)

    def name = column[String]("name".toUpperCase)

    def next_run_time = column[Option[Timestamp]]("next_run_time".toUpperCase)

    def cronExpression = column[Option[String]]("cronExpression".toUpperCase)

    def description = column[Option[String]]("description".toUpperCase)

    def up_status = column[Boolean]("up_status".toUpperCase)

    def * = (id, name, next_run_time, cronExpression, description, up_status).<>((JobInfo.apply _).tupled, JobInfo.unapply)
  }

  private val jobs = TableQuery[JobsTable]

  def create(job: JobInfo) = db.run(jobs.filter(_.id===job.id).map(f=>f.id).result)
    .flatMap{
      f=> if (f.nonEmpty){
        db.run(jobs.filter(_.id===job.id).update(job))
      }else{
        db.run(jobs returning jobs.map(_.id) += job)
      }
    }

  def findAll = db.run(jobs.sortBy(_.name).map(f => f).result)

  def findBy(id:String) = db.run(jobs.filter(_.id===id).map(f=>f).result)

  def upStatus(id: String, status: Boolean) = db.run(jobs.filter(_.id === id).map(_.up_status).update(status))

  def upNextRunTime(id: String, nrt: Timestamp) = db.run(jobs.filter(_.id === id).map(_.next_run_time).update(Some(nrt)))

  def delete(id:String) = db.run(jobs.filter(_.id === id).delete)
}
